package cn.iocoder.yudao.module.product.service.shopfavorite;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.product.api.conveniencestore.ProductConvenienceStoreApi;
import cn.iocoder.yudao.module.product.controller.admin.shopfavorite.vo.ShopFavoritePageReqVO;
import cn.iocoder.yudao.module.product.controller.admin.shopfavorite.vo.ShopFavoriteSaveReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.shopfavorite.ShopFavoriteDO;
import cn.iocoder.yudao.module.product.dal.mysql.shopfavorite.ShopFavoriteMapper;
import cn.iocoder.yudao.module.product.service.conveniencestore.ConvenienceStoreService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SHOP_FAVORITE_NOT_EXISTS;

/**
 * 商铺收藏 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ShopFavoriteServiceImpl implements ShopFavoriteService {

    @Resource
    private ShopFavoriteMapper shopFavoriteMapper;

    @Resource
    private ConvenienceStoreService convenienceStoreService;

    @Resource
    private ProductConvenienceStoreApi productConvenienceStoreApi;

    @Override
    public Long createShopFavorite(ShopFavoriteSaveReqVO createReqVO) {
        // 插入
        ShopFavoriteDO shopFavorite = BeanUtils.toBean(createReqVO, ShopFavoriteDO.class);
        shopFavoriteMapper.insert(shopFavorite);
        // 返回
        return shopFavorite.getId();
    }

    @Override
    public void updateShopFavorite(ShopFavoriteSaveReqVO updateReqVO) {
        // 校验存在
        //validateShopFavoriteExists(updateReqVO.getId());
        // 更新
        ShopFavoriteDO updateObj = BeanUtils.toBean(updateReqVO, ShopFavoriteDO.class);
        shopFavoriteMapper.updateById(updateObj);
    }

    @Override
    public void deleteShopFavorite(Long id) {
        // 校验存在
        validateShopFavoriteExists(id);
        // 删除
        shopFavoriteMapper.deleteById(id);
    }

    private void validateShopFavoriteExists(Long id) {
        if (shopFavoriteMapper.selectById(id) == null) {
            throw exception(SHOP_FAVORITE_NOT_EXISTS);
        }
    }

    @Override
    public ShopFavoriteDO getShopFavorite(Long id) {
        return shopFavoriteMapper.selectById(id);
    }

    @Override
    public PageResult<ShopFavoriteDO> getShopFavoritePage(ShopFavoritePageReqVO pageReqVO) {
        Long userId = WebFrameworkUtils.getLoginUserId();
        List<Long> myShopIds = productConvenienceStoreApi.getMyConvenienceStoreIdList(userId);
        return shopFavoriteMapper.selectPage(pageReqVO, myShopIds);
    }
}